<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\LayuiController as Layui;
use App\Models\UserPosition;
use Illuminate\Support\Facades\DB;
use App\Exceptions\FormException;
use Illuminate\Support\Facades\View;
use App\Http\Requests\PositionRequest;

class PositionController extends Controller
{
    /**
     * 职位列表
     *
     * @Author   qizhifei
     * @DateTime 2019-05-29
     * @param    Request $request [description]
     * @return   [type]              [description]
     */
    public function index(Request $request)
    {
        if ($request->isMethod('post')) {
            $departmentid = $request->input('department');
            $preData = UserPosition::
            when((isset($departmentid) && $departmentid != ''), function ($query) use ($departmentid) {
                $query->Where('department_id', $departmentid);
            })
                ->paginate($request->get('limit', 10));
            return Layui::tableJson($preData, 0, $preData->total());
        } else {
            return view('Admin.position.index');
        }
    }


    /**
     * 添加页面
     *
     * @Author   qizhifei
     * @DateTime 2019-05-29
     * @param    Request $request [description]
     * @return   [type]              [description]
     */
    public function create()
    {
        if (View::exists('Admin/position/add')) {
            return view('Admin/position/add');
        } else {
            return 'View Not Found';
        }
    }


    /**
     * 添加请求
     *
     * @Author   qizhifei
     * @DateTime 2019-05-29
     * @param    Request $request [description]
     * @return   [type]              [description]
     */
    public function store(PositionRequest $request)
    {
        $payload = $request->all(['number', 'position_name', 'department_id']);
        try {
            UserPosition::create($payload);
        } catch (\Exception $exception) {
            throw new FormException(\App::environment('local') ? $exception->getMessage() : '保存失败');
        }
        return $this->getResponseSuccess('保存成功', route('position.index'));
    }

    /**
     * 删除数据
     *
     * @Author   qizhifei
     * @DateTime 2019-05-31
     * @param    [type]     $id [description]
     * @return   [type]         [description]
     */
    public function destroy($id)
    {
        try {
            UserPosition::destroy($id);
        } catch (\Exception $exception) {
            throw new FormException(App::environment('local') ? $exception->getMessage() : '操作失败');
        }
        return $this->getResponse('操作成功');
    }


}
